/**
 * 这是一个获取网页授权的js文件
 */

const {appID,appsecret} = require('./config');
const https = require('https');

const {getOauthAccessToken} = require('./getAccessToken');

//刷新access_token
function RefreshAccessToken(access_token){
    return new Promise((resolve,reject)=>{
        //https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
        let uri = `https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${appID}&grant_type=refresh_token&refresh_token=${access_token}`;
        https.get(uri,res=>{
            let data = "";
            res.on('data',chunk=>data+=chunk);
            res.on('end',()=>{
                resolve(data);
            });
            res.on('error',err=>reject(err));
        })
    })
}

function getOauthUserInfo(CODE){
    return new Promise(async(resolve,reject)=>{
        let OauthAccessToken = await getOauthAccessToken(CODE)
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        https.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${OauthAccessToken.access_token}&openid=${OauthAccessToken.openid}&lang=zh_CN`,res=>{
            let data = "";
            res.on('data',chunk=>data += chunk);
            res.on('end',()=>{
                data = JSON.parse(data);
                resolve(data);
            });
            res.on('error',err=>reject(err));
        })
    });
}

/** */
function getOauthUserInfoFile(){
    return new Promise(async(resolve,reject)=>{
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        https.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${OauthAccessToken.access_token}&openid=${OauthAccessToken.openid}&lang=zh_CN`,res=>{
            let data = "";
            res.on('data',chunk=>data += chunk);
            res.on('end',()=>{
                data = JSON.parse(data);
                resolve(data);
            });
            res.on('error',err=>reject(err));
        })
    });
}

module.exports = {
    RefreshAccessToken,getOauthUserInfo
    
}